package cn.nawang.ebeim.client.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import cn.nawang.ebeim.client.bean.ClientConfiguration;
import cn.nawang.ebeim.client.bean.FileBackupTask;
import cn.nawang.ebeim.client.bean.RecoveryTask;
import cn.nawang.ebeim.client.bean.UserBehaviorsLog;

public class UserBehaviorsUploadUtils {
    public static final long FILE_SIZE = 1024 * 1024;
    public static final String FILE_SUFFIX = ".bhs";
    public static final String FILE_DIR = "behaviors";
    public static final String SERVICE_UPLOAD_URL =
            ClientConfiguration.getApiHost() + "/ebeim-api/api/userBeHaviorsLog/upload";

    private static String getLogPath(String dsId) {
        return FileUtil.getDataSourcePath(dsId) + File.separator + FILE_DIR;
    }

    private static void fileUpload(String url, String filename) {
        String userID = PropertiesUtil.read(PropertiesConstants.USER_ID);
        if (userID == null) return;
        HttpClient httpclient = new DefaultHttpClient();
        File logFile = new File(filename);
        try {
            HttpPost httppost = new HttpPost(url);
            httppost.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
                    Charset.forName("UTF-8"));

            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    null, Charset.forName("UTF-8"));
            reqEntity.addPart("file", new FileBody(logFile));
            reqEntity.addPart("userID", new StringBody(userID));
            httppost.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(httppost);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == HttpStatus.SC_OK) {
                System.out.println("服务器正常响应.....");
                HttpEntity resEntity = response.getEntity();
                System.out.println(resEntity.getContent());
                EntityUtils.consume(resEntity);
                logFile.delete();
            }

        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {

            }
        }
    }

    public static synchronized void uploadAllFile(String dsId, String action) {
        File dir = new File(getLogPath(dsId));
        String[] childrens = dir.list();
        if (childrens != null) for (String childfile : childrens) {
            if (childfile.startsWith(action)) {
                fileUpload(SERVICE_UPLOAD_URL, getLogPath(dsId) + File.separator + childfile);
            }
        }
    }

    private static String getName(UserBehaviorsLog userBehaviorsLog) {
        return userBehaviorsLog.getAction() + FILE_SUFFIX;
    }

    private static String getReName(UserBehaviorsLog userBehaviorsLog) {
        return userBehaviorsLog.getAction() + UUID.randomUUID() + FILE_SUFFIX;
    }

    public synchronized static void wirteToFile(UserBehaviorsLog userBehaviorsLog) {
        String savePath = getLogPath(userBehaviorsLog.getDsId());

        File dir = new File(savePath);

        File txt = new File(savePath + File.separator + getName(userBehaviorsLog));
        FileWriter writer = null;
        try {
            if (!dir.exists()) {
                dir.mkdirs();
            }

            if (!txt.exists()) {
                txt.createNewFile();
            }

            if (txt.length() > FILE_SIZE) {
                txt.renameTo(new File(savePath + File.separator + getReName(userBehaviorsLog)));
                wirteToFile(userBehaviorsLog);
            }
            writer = new FileWriter(txt, true);
            writer.write(new Gson().toJson(userBehaviorsLog));
            writer.write(System.getProperty("line.separator"));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    public static void logToFile(Object info, String targetPath, long beginTime, String action,
            String result) {
        try {
            UserBehaviorsLog userBehaviorsLog = new UserBehaviorsLog();
            userBehaviorsLog.setAction(action);
            userBehaviorsLog.setResult(result);
            userBehaviorsLog.setBeginTime(beginTime);
            userBehaviorsLog.setEndTime(new Date().getTime());
            userBehaviorsLog.setElapsedTime(
                    userBehaviorsLog.getEndTime() - userBehaviorsLog.getBeginTime());

            if (UserBehaviorsLog.ACTION_DOWANLOAD.equals(action)) {
                RecoveryTask recoveryTask = (RecoveryTask) info;
                userBehaviorsLog.setDsId(recoveryTask.getDataSourceId());
            } else {
                FileBackupTask fileBackupTask = (FileBackupTask) info;
                userBehaviorsLog.setDsId(fileBackupTask.getDataSource().getId());
                if (fileBackupTask.getDataSource() != null
                        && fileBackupTask.getDataSource().getRoot() != null) {
                    targetPath = fileBackupTask.getDataSource().getRoot();
                    if (fileBackupTask.getInfo() != null
                            && fileBackupTask.getInfo().getPath() != null) {
                        targetPath += fileBackupTask.getInfo().getPath();
                        if(fileBackupTask.getInfo().getName() != null)
                        targetPath += File.separator + fileBackupTask.getInfo().getName();
                    }
                }
            }
            userBehaviorsLog.setTargetPath(targetPath.replace("/", "").replace("\\\\", "\\"));
            userBehaviorsLog.setLog(new Gson().toJson(info));
            UserBehaviorsUploadUtils.wirteToFile(userBehaviorsLog);
        } catch (Exception e) {

        }
    }



    // public static void main(String[] args) {
    // wirteToFile("DS-1447815698017-418", "sdfdsf");
    // }
    public static void main(String[] args) {
        fileUpload("http://127.0.0.1:8080/ebeim-api/api/userBeHaviorsLog/upload", "F:\\aaa.txt");
        for (int i = 0; i < -1; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        fileUpload("http://127.0.0.1:8080/ebeim-api/api/userBeHaviorsLog/upload",
                                "E:\\workspace\\ebeim-client\\behaviors\\中behaviors.txt");
                        // wirteToFile("{\"a7666666666666666666666666666666666666666666666666666666666666666666666666666666a\":\"b237489237474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474b\"}");
                    }

                }
            }).start();
        }
    }

}
